package com.tust.androidbbsclient;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.tust.androidbbsclient.adapter.ArtDetailCommentRecyclerAdapter;
import com.tust.androidbbsclient.tool.Application;
import com.tust.androidbbsclient.tool.Tool;
import com.tust.androidbbsclient.trans.CommentDetail;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ArticleDetailActivity extends AppCompatActivity {
    private Toast toast;
    private Context context;
    private int UID;
    private int ArtID;
    private int isFavored;
    private int isCollected;
    private int UbanLevel;

    RecyclerView recyclerViewArtDetailComment;
    ArtDetailCommentRecyclerAdapter artDetailCommentRecyclerAdapter;

    TextView textViewArtDetailUname;
    TextView textViewtvArtDetailArtSubTime;
    TextView textViewArtDetailArtcategory;
    TextView textViewArtDetailArtTitle;
    TextView textViewArtDetailArtContent;
    TextView textViewArtDetailArtFavorNum;
    TextView textViewArtDetailArtCollNum;
    ImageView imageViewArtDetailArtPic1;
    ImageView imageViewArtDetailArtPic2;
    ImageView imageViewArtDetailArtPic3;
    ImageView imageViewArtDetailArtPic4;
    ImageView imageViewArtDetailArtPic5;
    ImageView imageViewArtDetailArtPic6;
    ImageView imageViewArtDetailArtFavorIcon;
    ImageView imageViewArtDetailArtCollIcon;
    EditText editTextArtDetailComment;

    String artPic1;
    String artPic2;
    String artPic3;
    String artPic4;
    String artPic5;
    String artPic6;

    //用于在线程间传递消息
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);//获取子线程传递的消息
            if (msg.what == 1) {//显示贴文详情请求返回值
                String strMsg = msg.obj.toString();
                //System.out.println("显示贴文详情：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else {
                    //解析JSON字符串
                    try {
                        JSONArray jsonArray = new JSONArray(strMsg);
                        textViewArtDetailUname.setText(jsonArray.getJSONObject(0).getString("uname"));
                        textViewtvArtDetailArtSubTime.setText(jsonArray.getJSONObject(0).getString("artSubTime"));
                        textViewArtDetailArtcategory.setText(jsonArray.getJSONObject(0).getString("artCategory"));
                        textViewArtDetailArtTitle.setText(jsonArray.getJSONObject(0).getString("artTitle"));
                        textViewArtDetailArtContent.setText(jsonArray.getJSONObject(0).getString("artContent"));
                        textViewArtDetailArtFavorNum.setText(jsonArray.getJSONObject(0).getString("artFavorNum"));
                        textViewArtDetailArtCollNum.setText(jsonArray.getJSONObject(0).getString("artCollNum"));

                        artPic1 = jsonArray.getJSONObject(0).getString("artPic1").replaceAll("dataimage/jpegbase64", "");
                        artPic2 = jsonArray.getJSONObject(0).getString("artPic2").replaceAll("dataimage/jpegbase64", "");
                        artPic3 = jsonArray.getJSONObject(0).getString("artPic3").replaceAll("dataimage/jpegbase64", "");
                        artPic4 = jsonArray.getJSONObject(0).getString("artPic4").replaceAll("dataimage/jpegbase64", "");
                        artPic5 = jsonArray.getJSONObject(0).getString("artPic5").replaceAll("dataimage/jpegbase64", "");
                        artPic6 = jsonArray.getJSONObject(0).getString("artPic6").replaceAll("dataimage/jpegbase64", "");
                        if (!artPic1.equals("null")) imageViewArtDetailArtPic1.setImageBitmap(BitmapFactory.decodeByteArray(Base64.decode(artPic1, Base64.DEFAULT), 0, Base64.decode(artPic1, Base64.DEFAULT).length));
                        else imageViewArtDetailArtPic1.setVisibility(View.GONE);
                        if (!artPic2.equals("null")) imageViewArtDetailArtPic2.setImageBitmap(BitmapFactory.decodeByteArray(Base64.decode(artPic2, Base64.DEFAULT), 0, Base64.decode(artPic2, Base64.DEFAULT).length));
                        else imageViewArtDetailArtPic2.setVisibility(View.GONE);
                        if (!artPic3.equals("null")) imageViewArtDetailArtPic3.setImageBitmap(BitmapFactory.decodeByteArray(Base64.decode(artPic3, Base64.DEFAULT), 0, Base64.decode(artPic3, Base64.DEFAULT).length));
                        else imageViewArtDetailArtPic3.setVisibility(View.GONE);
                        if (!artPic4.equals("null")) imageViewArtDetailArtPic4.setImageBitmap(BitmapFactory.decodeByteArray(Base64.decode(artPic4, Base64.DEFAULT), 0, Base64.decode(artPic4, Base64.DEFAULT).length));
                        else imageViewArtDetailArtPic4.setVisibility(View.GONE);
                        if (!artPic5.equals("null")) imageViewArtDetailArtPic5.setImageBitmap(BitmapFactory.decodeByteArray(Base64.decode(artPic5, Base64.DEFAULT), 0, Base64.decode(artPic5, Base64.DEFAULT).length));
                        else imageViewArtDetailArtPic5.setVisibility(View.GONE);
                        if (!artPic6.equals("null")) imageViewArtDetailArtPic6.setImageBitmap(BitmapFactory.decodeByteArray(Base64.decode(artPic6, Base64.DEFAULT), 0, Base64.decode(artPic6, Base64.DEFAULT).length));
                        else imageViewArtDetailArtPic6.setVisibility(View.GONE);

                        isFavored = Integer.parseInt(jsonArray.getJSONObject(0).getString("isFavored"));
                        isCollected = Integer.parseInt(jsonArray.getJSONObject(0).getString("isCollected"));

                        if (isFavored == 1) imageViewArtDetailArtFavorIcon.setColorFilter(ContextCompat.getColor(context , R.color.orange));
                        if (isCollected == 1) imageViewArtDetailArtCollIcon.setColorFilter(ContextCompat.getColor(context , R.color.orange));
                      } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            } else if (msg.what == 2) {//展示贴文评论请求返回值
                String strMsg = msg.obj.toString();
                //System.out.println("显示评论：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else setRecyclerView(strMsg);//调用RecyclerView设置方法
            } else if (msg.what == 3) {//插入评论请求返回值
                String strMsg = msg.obj.toString();
                //System.out.println("提交评论：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "databaseFalse":
                        showToast(Tool.addEmoji() + "服务器端错误！");
                        break;
                    case "userBaning":
                        showToast(Tool.addEmoji() + "您已被禁言！");
                        break;
                    case "insertCommentFalse":
                        showToast(Tool.addEmoji() + "评论提交失败！");
                        break;
                    case "insertCommentSuccess":
                        showToast(Tool.addEmoji() + "评论提交成功，等待审核！");
                        break;
                }
            } else if (msg.what == 4) {//点赞贴文请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("点赞贴文：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "databaseFalse":
                        showToast(Tool.addEmoji() + "服务器端错误！");
                        break;
                    case "insertFavorFalse":
                        showToast(Tool.addEmoji() + "点赞失败！");
                        break;
                    case "insertFavorSuccess":
                        showToast(Tool.addEmoji() + "点赞成功！");
                        isFavored = 1;
                        textViewArtDetailArtFavorNum.setText(String.valueOf(Integer.parseInt(textViewArtDetailArtFavorNum.getText().toString()) + 1));//刷新控件
                        imageViewArtDetailArtFavorIcon.setColorFilter(ContextCompat.getColor(context, R.color.orange));
                        break;
                }
            } else if (msg.what == 5) {//收藏贴文请求
                String strMsg = msg.obj.toString();
                System.out.println("收藏贴文：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "databaseFalse":
                        showToast(Tool.addEmoji() + "服务器端错误！");
                        break;
                    case "insertCollectionFalse":
                        showToast(Tool.addEmoji() + "收藏失败！");
                        break;
                    case "insertCollectionSuccess":
                        showToast(Tool.addEmoji() + "收藏成功！");
                        isCollected = 1;
                        textViewArtDetailArtCollNum.setText(String.valueOf(Integer.parseInt(textViewArtDetailArtCollNum.getText().toString()) + 1));//刷新控件
                        imageViewArtDetailArtCollIcon.setColorFilter(ContextCompat.getColor(context, R.color.orange));
                        break;
                }
            } else if (msg.what == 6) {//取消点赞贴文请求
                String strMsg = msg.obj.toString();
                System.out.println("取消点赞：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "deleteFavorFalse":
                        showToast(Tool.addEmoji() + "取消点赞失败！");
                        break;
                    case "deleteFavorSuccess":
                        showToast(Tool.addEmoji() + "取消点赞成功！");
                        isFavored = 0;
                        textViewArtDetailArtFavorNum.setText(String.valueOf(Integer.parseInt(textViewArtDetailArtFavorNum.getText().toString()) - 1));//刷新控件

                        imageViewArtDetailArtFavorIcon.setColorFilter(null);
                        break;
                }
            } else if (msg.what == 7) {//取消收藏贴文请求
                String strMsg = msg.obj.toString();
                System.out.println("取消收藏：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "deleteCollectionFalse":
                        showToast(Tool.addEmoji() + "取消收藏失败！");
                        break;
                    case "deleteCollectionSuccess":
                        showToast(Tool.addEmoji() + "取消收藏成功！");
                        isCollected = 0;
                        textViewArtDetailArtCollNum.setText(String.valueOf(Integer.parseInt(textViewArtDetailArtCollNum.getText().toString()) - 1));//刷新控件

                        imageViewArtDetailArtCollIcon.setColorFilter(null);
                        break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_articledetail);

        Application application = (Application) getApplication();
        context = application.getContext();

        recyclerViewArtDetailComment = this.findViewById(R.id.rv_artDetailComment);

        textViewArtDetailUname = this.findViewById(R.id.tv_artDetailUname);
        textViewtvArtDetailArtSubTime = this.findViewById(R.id.tv_artDetailArtSubTime);
        textViewArtDetailArtcategory = this.findViewById(R.id.tv_artDetailArtCategory);
        textViewArtDetailArtTitle = this.findViewById(R.id.tv_artDetailArtTitle);
        textViewArtDetailArtContent = this.findViewById(R.id.tv_artDetailArtContent);
        textViewArtDetailArtFavorNum = this.findViewById(R.id.tv_artDetailArtFavorNum);
        textViewArtDetailArtCollNum = this.findViewById(R.id.tv_artDetailArtCollNum);
        imageViewArtDetailArtPic1 = this.findViewById(R.id.iv_artDetailArtPic1);
        imageViewArtDetailArtPic2 = this.findViewById(R.id.iv_artDetailArtPic2);
        imageViewArtDetailArtPic3 = this.findViewById(R.id.iv_artDetailArtPic3);
        imageViewArtDetailArtPic4 = this.findViewById(R.id.iv_artDetailArtPic4);
        imageViewArtDetailArtPic5 = this.findViewById(R.id.iv_artDetailArtPic5);
        imageViewArtDetailArtPic6 = this.findViewById(R.id.iv_artDetailArtPic6);
        imageViewArtDetailArtFavorIcon = this.findViewById(R.id.iv_artDetailArtFavorIcon);
        imageViewArtDetailArtCollIcon = this.findViewById(R.id.iv_artDetailArtCollIcon);
        editTextArtDetailComment = this.findViewById(R.id.et_artDetailComment);

        LinearLayout linearLayoutArtDetailArtFavor = this.findViewById(R.id.ll_artDetailArtFavor);
        LinearLayout linearLayoutArtDetailArtColl = this.findViewById(R.id.ll_artDetailArtColl);
        ImageButton imageButtonArtDetailSubmitComment = this.findViewById(R.id.ibtn_artDetailSubmitComment);
        FloatingActionButton floatingActionButtonArtDetailComment = this.findViewById(R.id.fab_artDetailComment);

        //从意图中获得贴文ID和用户ID
        ArtID = this.getIntent().getIntExtra("ArtID", -1);

        //从Application中获得用户信息
        UID = application.user.getUID();
        UbanLevel = application.user.getUbanLevel();

        if (UbanLevel == -1) {//禁言状态
            //设置评论输入框不可编辑
            editTextArtDetailComment.setHint("您已被禁言！");
            editTextArtDetailComment.setFocusable(false);
            editTextArtDetailComment.setEnabled(false);
        }

        //发送显示贴文详情请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/showArticleDetail.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(10000);//连接服务器超时
                    connection.setReadTimeout(10000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式
                    connection.setRequestProperty("Connection", "Keep-Alive");//大数据保持连接

                    connection.connect();//连接网络
                    String params = "ArtID=" + ArtID + "&UID=" + UID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //发送展示贴文评论请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 2;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/showArtComment.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(5000);//连接服务器超时
                    connection.setReadTimeout(5000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "ArtID=" + ArtID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 2;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //贴文详情用户名文本监听事件
        textViewArtDetailUname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showToast(Tool.addEmoji() + "正在打开“" + textViewArtDetailUname.getText().toString() + "”的访客空间！");

                //跳转活动
                Intent intent = new Intent(context, VisitorActivity.class);
                intent.putExtra("UID", UID);
                context.startActivity(intent);
                overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

       //评论图片按钮监听事件
        imageButtonArtDetailSubmitComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UbanLevel != -1) {//不是禁言状态
                    String ComContent = editTextArtDetailComment.getText().toString();

                    if (ComContent.equals("")) showToast(Tool.addEmoji() + "请输入评论内容！");
                    else {
                        //发送插入评论请求子线程
                        new Thread() {
                            @Override
                            public void run() {
                                OutputStream outputStream = null;
                                BufferedReader bufferedReader = null;
                                String data = "";
                                try {
                                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                    handlerMsg.what = 3;//增加handlerMsg标识符

                                    URL url = new URL(Tool.InetAddress + "/insertComment.do");//请求地址
                                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                    //连接类相关设置
                                    connection.setRequestMethod("POST");
                                    connection.setConnectTimeout(3000);//连接服务器超时
                                    connection.setReadTimeout(3000);//从服务器读取数据超时
                                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                                    connection.setDoOutput(true);//允许写出，开启Post请求体
                                    connection.setUseCaches(false);//不使用Cache
                                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式
                                    connection.setRequestProperty("Connection", "Keep-Alive");//大数据保持连接

                                    connection.connect();//连接网络
                                    String params = "UID=" + UID + "&ArtID=" + ArtID + "&ComContent=" + ComContent;//请求体内容
                                    outputStream = connection.getOutputStream();//请求输出流
                                    outputStream.write(params.getBytes());

                                    int code = connection.getResponseCode();//获得响应状态码
                                    if (code == 200) {//返回状态码200，连接成功
                                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                        data = bufferedReader.readLine();

                                        handlerMsg.obj = data;//写入线程传递消息
                                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                                    connection.disconnect();//关闭连接

                                    handler.sendMessage(handlerMsg);//发送线程消息
                                } catch (IOException e) {
                                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                    handlerMsg.what = 3;//增加handlerMsg标识符
                                    handlerMsg.obj = "serverFalse";
                                    handler.sendMessage(handlerMsg);

                                    //throw new RuntimeException(e);
                                } finally {
                                    try {
                                        if (bufferedReader != null) bufferedReader.close();
                                        if (outputStream != null) {
                                            outputStream.flush();
                                            outputStream.close();
                                        }
                                    } catch (IOException e) {
                                        System.out.println("子线程：finally失败");
                                        //throw new RuntimeException(e);
                                    }
                                }
                            }
                        }.start();
                        editTextArtDetailComment.setText("");
                    }
                }
            }
        });

        //点赞LinearLayout监听事件
        linearLayoutArtDetailArtFavor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isFavored == 0) {
                    //发送点赞贴文请求子线程
                    new Thread() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            BufferedReader bufferedReader = null;
                            String data = "";
                            try {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 4;//增加handlerMsg标识符

                                URL url = new URL(Tool.InetAddress + "/favorateArticle.do");//请求地址
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                //连接类相关设置
                                connection.setRequestMethod("POST");
                                connection.setConnectTimeout(3000);//连接服务器超时
                                connection.setReadTimeout(3000);//从服务器读取数据超时
                                connection.setDoInput(true);//允许写入，从服务端读取结果流
                                connection.setDoOutput(true);//允许写出，开启Post请求体
                                connection.setUseCaches(false);//不使用Cache
                                connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                connection.connect();//连接网络
                                String params = "ArtID=" + ArtID + "&UID=" + UID;//请求体内容
                                outputStream = connection.getOutputStream();//请求输出流
                                outputStream.write(params.getBytes());

                                int code = connection.getResponseCode();//获得响应状态码
                                if (code == 200) {//返回状态码200，连接成功
                                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                    data = bufferedReader.readLine();

                                    handlerMsg.obj = data;//写入线程传递消息
                                } else handlerMsg.obj = "serverFalse";//服务器通信失败
                                connection.disconnect();//关闭连接

                                handler.sendMessage(handlerMsg);//发送线程消息
                            } catch (IOException e) {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 4;//增加handlerMsg标识符
                                handlerMsg.obj = "serverFalse";
                                handler.sendMessage(handlerMsg);

                                //throw new RuntimeException(e);
                            } finally {
                                try {
                                    if (bufferedReader != null) bufferedReader.close();
                                    if (outputStream != null) {
                                        outputStream.flush();
                                        outputStream.close();
                                    }
                                } catch (IOException e) {
                                    System.out.println("子线程：finally失败");
                                    //throw new RuntimeException(e);
                                }
                            }
                        }
                    }.start();
                    isFavored = -1;
                } else {
                    //发送取消点赞贴文请求子线程
                    new Thread() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            BufferedReader bufferedReader = null;
                            String data = "";
                            try {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 6;//增加handlerMsg标识符

                                URL url = new URL(Tool.InetAddress + "/cancelFavorateArticle.do");//请求地址
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                //连接类相关设置
                                connection.setRequestMethod("POST");
                                connection.setConnectTimeout(3000);//连接服务器超时
                                connection.setReadTimeout(3000);//从服务器读取数据超时
                                connection.setDoInput(true);//允许写入，从服务端读取结果流
                                connection.setDoOutput(true);//允许写出，开启Post请求体
                                connection.setUseCaches(false);//不使用Cache
                                connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                connection.connect();//连接网络
                                String params = "ArtID=" + ArtID + "&UID=" + UID;//请求体内容
                                outputStream = connection.getOutputStream();//请求输出流
                                outputStream.write(params.getBytes());

                                int code = connection.getResponseCode();//获得响应状态码
                                if (code == 200) {//返回状态码200，连接成功
                                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                    data = bufferedReader.readLine();

                                    handlerMsg.obj = data;//写入线程传递消息
                                } else handlerMsg.obj = "serverFalse";//服务器通信失败
                                connection.disconnect();//关闭连接

                                handler.sendMessage(handlerMsg);//发送线程消息
                            } catch (IOException e) {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 6;//增加handlerMsg标识符
                                handlerMsg.obj = "serverFalse";
                                handler.sendMessage(handlerMsg);

                                //throw new RuntimeException(e);
                            } finally {
                                try {
                                    if (bufferedReader != null) bufferedReader.close();
                                    if (outputStream != null) {
                                        outputStream.flush();
                                        outputStream.close();
                                    }
                                } catch (IOException e) {
                                    System.out.println("子线程：finally失败");
                                    //throw new RuntimeException(e);
                                }
                            }
                        }
                    }.start();
                    isFavored = -1;
                }
            }
        });

        //收藏LinearLayout监听事件
        linearLayoutArtDetailArtColl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCollected == 0) {
                    //发送收藏贴文请求子线程
                    new Thread() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            BufferedReader bufferedReader = null;
                            String data = "";
                            try {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 5;//增加handlerMsg标识符

                                URL url = new URL(Tool.InetAddress + "/collectArticle.do");//请求地址
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                //连接类相关设置
                                connection.setRequestMethod("POST");
                                connection.setConnectTimeout(3000);//连接服务器超时
                                connection.setReadTimeout(3000);//从服务器读取数据超时
                                connection.setDoInput(true);//允许写入，从服务端读取结果流
                                connection.setDoOutput(true);//允许写出，开启Post请求体
                                connection.setUseCaches(false);//不使用Cache
                                connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                connection.connect();//连接网络
                                String params = "ArtID=" + ArtID + "&UID=" + UID;//请求体内容
                                outputStream = connection.getOutputStream();//请求输出流
                                outputStream.write(params.getBytes());

                                int code = connection.getResponseCode();//获得响应状态码
                                if (code == 200) {//返回状态码200，连接成功
                                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                    data = bufferedReader.readLine();

                                    handlerMsg.obj = data;//写入线程传递消息
                                } else handlerMsg.obj = "serverFalse";//服务器通信失败
                                connection.disconnect();//关闭连接

                                handler.sendMessage(handlerMsg);//发送线程消息
                            } catch (IOException e) {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 5;//增加handlerMsg标识符
                                handlerMsg.obj = "serverFalse";
                                handler.sendMessage(handlerMsg);

                                //throw new RuntimeException(e);
                            } finally {
                                try {
                                    if (bufferedReader != null) bufferedReader.close();
                                    if (outputStream != null) {
                                        outputStream.flush();
                                        outputStream.close();
                                    }
                                } catch (IOException e) {
                                    System.out.println("子线程：finally失败");
                                    //throw new RuntimeException(e);
                                }
                            }
                        }
                    }.start();
                    isCollected = -1;
                } else {
                    //发送取消收藏贴文请求子线程
                    new Thread() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            BufferedReader bufferedReader = null;
                            String data = "";
                            try {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 7;//增加handlerMsg标识符

                                URL url = new URL(Tool.InetAddress + "/cancelCollectArticle.do");//请求地址
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                //连接类相关设置
                                connection.setRequestMethod("POST");
                                connection.setConnectTimeout(3000);//连接服务器超时
                                connection.setReadTimeout(3000);//从服务器读取数据超时
                                connection.setDoInput(true);//允许写入，从服务端读取结果流
                                connection.setDoOutput(true);//允许写出，开启Post请求体
                                connection.setUseCaches(false);//不使用Cache
                                connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                connection.connect();//连接网络
                                String params = "ArtID=" + ArtID + "&UID=" + UID;//请求体内容
                                outputStream = connection.getOutputStream();//请求输出流
                                outputStream.write(params.getBytes());

                                int code = connection.getResponseCode();//获得响应状态码
                                if (code == 200) {//返回状态码200，连接成功
                                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                    data = bufferedReader.readLine();

                                    handlerMsg.obj = data;//写入线程传递消息
                                } else handlerMsg.obj = "serverFalse";//服务器通信失败
                                connection.disconnect();//关闭连接

                                handler.sendMessage(handlerMsg);//发送线程消息
                            } catch (IOException e) {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 7;//增加handlerMsg标识符
                                handlerMsg.obj = "serverFalse";
                                handler.sendMessage(handlerMsg);

                                //throw new RuntimeException(e);
                            } finally {
                                try {
                                    if (bufferedReader != null) bufferedReader.close();
                                    if (outputStream != null) {
                                        outputStream.flush();
                                        outputStream.close();
                                    }
                                } catch (IOException e) {
                                    System.out.println("子线程：finally失败");
                                    //throw new RuntimeException(e);
                                }
                            }
                        }
                    }.start();
                    isCollected = -1;
                }
            }
        });

        //悬浮按钮监听事件
        floatingActionButtonArtDetailComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recyclerViewArtDetailComment.smoothScrollToPosition(0);//平滑滚动到顶部
            }
        });
    }

    //设置RecyclerView
    private void setRecyclerView(String comDetailData) {
        List<CommentDetail> commentDetails = new ArrayList<>();
        //解析JSON字符串
        try {
            JSONArray jsonArray = new JSONArray(comDetailData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                commentDetails.add(
                        new CommentDetail(
                                Integer.parseInt(jsonObject.getString("uid")),
                                jsonObject.getString("uname"),
                                jsonObject.getString("comContent"),
                                jsonObject.getString("comTime")
                        )
                );
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        if (commentDetails.size() > 0) showToast(Tool.addEmoji() + "已请求到数据，正在加载！");
        else showToast(Tool.addEmoji() + "没有评论！");

        artDetailCommentRecyclerAdapter = new ArtDetailCommentRecyclerAdapter(this, this, commentDetails);//构造Recycler适配器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);//创建线性布局管理器,默认子项布局垂直方向
        linearLayoutManager.setReverseLayout(false);//子项布局从顶部开始排列
        recyclerViewArtDetailComment.setLayoutManager(linearLayoutManager);//为RecyclerView设置布局管理器
        recyclerViewArtDetailComment.setAdapter(artDetailCommentRecyclerAdapter);//为RecyclerView设置适配器
    }

    //Toast消息提示框显示方法
    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}
